import 'dart:convert' as convert;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/route_manager.dart' as Gets;
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_profit/mine_profit_page/widget/add_bank_dialog.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_alert_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';

import '../../../../alert_business/normal_alert_style.dart';
import '../../../../hj_utils/global.dart';
import '../../../../hj_utils/light_model.dart';
import '../../../../hj_utils/store_keys.dart';
import '../../../../tools_base/refresh/pull_refresh.dart';
import 'model/alipay_bank_list_model.dart';

///银行卡管理
class BankCardHomePage extends StatefulWidget {
  final AccountInfoModel? selectModel;
  BankCardHomePage({super.key, this.selectModel});

  @override
  State<StatefulWidget> createState() {
    return _BankCardHomePageState();
  }
}

class _BankCardHomePageState extends State<BankCardHomePage> {
  bool isEdit = false;

  bool loading = true;

  List<AccountInfoModel> aliList = [];

  AccountInfoModel? selectItem;
  List<AccountInfoModel> deleteList = [];
  RefreshController? refreshCtr;

  @override
  void initState() {
    super.initState();
    _getAliListData();
  }

  void _onDeleteAccount() async {
    if (deleteList.isEmpty) return;
    var isDelete = await showConfirm(content: "是否确认删除账号", showCancelBtn: true);
    if (isDelete == null || !isDelete) {
      return;
    }
    LoadingAlertWidget.show();
    bool result = false;
    for (var model in deleteList) {
      result = await MineService.bankCardDelete(id: model.id);
      if (result) {
        var result = await lightKV.getString(StoreKeys.LAST_A_ACCOUNT);
        if (result != null) {
          AccountInfoModel listBean = AccountInfoModel.fromMap(convert.jsonDecode(result));
          if (model.id == listBean.id) {
            lightKV.setString(StoreKeys.LAST_A_ACCOUNT, "");
          }
        }
        aliList.remove(model);
        setState(() {});
      }
    }
    if (result) {
      showToast("删除成功");
      isEdit = false;
      if (mounted) setState(() {});
    }
    LoadingAlertWidget.cancel();
  }

  void _getAliListData() async {
    final model = await MineService.getBankCardList();
    aliList.clear();
    aliList.addAll(model?.list ?? []);
    refreshCtr?.refreshCompleted();
    if (aliList.isNotEmpty == true) {
      if (widget.selectModel != null) {
        selectItem = widget.selectModel;
      } else {
        // selectItem = aliList.firstOrNull;
      }
    }
    loading = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text('选择银行卡', style: textStyle(18, Color(0xE5FFFFFF), FontWeight.w600)),
        leading: BackButton(
          onPressed: () => Get.back(result: selectItem),
        ),
        actions: [
          InkWell(
            onTap: () {
              isEdit = !isEdit;
              if (isEdit) {
                deleteList.clear();
              }
              setState(() {});
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              child: Text(
                isEdit ? "完成" : "编辑",
                style: TextStyle(
                  color: isEdit ? AppColors.actionRed : Color(0x8CFFFFFF),
                  fontSize: 12,
                ),
              ),
            ),
          ),
          18.sizeBoxW,
        ],
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Column(
            children: [
              Expanded(child: () {
                if (loading) return LoadingCenterWidget();
                if (aliList.isEmpty == true) return CErrorWidget();
                return Container(
                  margin: EdgeInsets.fromLTRB(16, 12, 16, 0),
                  child: pullYsRefresh(
                    onInit: (ctr) => refreshCtr = ctr,
                    enablePullUp: false,
                    onRefresh: (ctr) => _getAliListData(),
                    child: ListView.builder(
                      padding: EdgeInsets.only(top: 10, bottom: 80),
                      shrinkWrap: true,
                      itemCount: aliList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return _buildCardView(index, aliList[index]);
                      },
                    ),
                  ),
                );
              }()),
              _buildCardAddView(),
            ],
          ),
          if (isEdit)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: GestureDetector(
                onTap: () => _onDeleteAccount(),
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 35, vertical: 20),
                  height: 44,
                  decoration: BoxDecoration(
                    color: Color(0xffF52C56),
                    borderRadius: const BorderRadius.all(Radius.circular(3)),
                  ),
                  child: Center(
                    child: Text(
                      "删除",
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildCardView(int index, AccountInfoModel? item) {
    bool isSelected = false;
    if (isEdit) {
      if (deleteList.contains(item) == true) {
        isSelected = true;
      }
    } else {
      isSelected = selectItem?.id == item?.id;
    }
    return InkWell(
      onTap: () {
        if (isEdit) {
          if (deleteList.contains(item) == true) {
            deleteList.remove(item);
          } else {
            deleteList.add(item!);
          }
        } else {
          Get.back(result: item);
        }
        setState(() {});
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 12),
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 18),
        decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(9)), color: const Color(0x0DFFFFFF)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        item?.getBankName() ?? "",
                        style: const TextStyle(color: const Color(0xE5ffffff), fontWeight: FontWeight.w500, fontSize: 16.0),
                      ),
                      9.sizeBoxW,
                      Text(
                        item?.actName ?? "",
                        style: const TextStyle(color: const Color(0xE5ffffff), fontWeight: FontWeight.w400, fontSize: 12.0),
                      )
                    ],
                  ),
                  6.sizeBoxH,
                  Text("卡号:${item?.act}",
                      style: const TextStyle(color: const Color(0xffffffff), fontWeight: FontWeight.w400, fontSize: 12.0))
                ],
              ),
            ),
            Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  width: 18,
                  height: 18,
                  decoration: BoxDecoration(
                    color: isSelected ? Colors.white : Colors.transparent,
                    shape: BoxShape.circle,
                  ),
                ),
                Icon(
                  isSelected ? CupertinoIcons.checkmark_circle_fill : CupertinoIcons.circle,
                  color: isSelected ? Color(0xffE1351F) : Color(0xff999999),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  //添加银行卡
  _buildCardAddView() {
    return InkWell(
      onTap: () async {
        final res = await Get.dialog(AddBankDialog(), barrierColor: Colors.black.withOpacity(.7));
        if (res != null) {
          _getAliListData();
        }
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 35, vertical: 20),
        height: 44,
        decoration: BoxDecoration(
          color: AppColors.actionRed,
          borderRadius: const BorderRadius.all(Radius.circular(3)),
        ),
        child: Center(
          child: Text(
            "添加银行卡",
            style: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w500,
              fontSize: 16,
            ),
          ),
        ),
      ),
    );
  }
}
